#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import cgi
import json
import db_conf
import time
con = None

def insert_peak_sql():
    return """INSERT INTO spectral_peak (spectrum_id, mz, intensity) VALUES (%s,%s,%s)"""

try:
    #print time.asctime( time.localtime(time.time()) )	
    qform = cgi.FieldStorage()
    compound_id = qform.getvalue('compound_id')	    	
    spa_delete = qform.getvalue('spa_delete')
    mz = qform.getvalue('spa_peak_mz')
    formula = qform.getvalue('spa_formula')
    isotope_mass_max = qform.getvalue('spa_isotope_max_mass')
    label_confirm = qform.getvalue('spa_confirm')
    inchi = qform.getvalue('spa_inchi')
    spectrum_annotation_id = qform.getvalue('spa_id')
    comment = qform.getvalue('spa_comment')
    precursor_atoms_retained =qform.getvalue('precursor_atoms_retained')
    ops = qform.getvalue('ops')
    update_spa_sql = ""
    #INSERT INTO spectrum_annotation (compound_id,mz,formula,inchi,comment,mass_isotopomer_max) VALUES (0 /*not nullable*/,0,'s','s','s',0);
    if (spa_delete == None or spa_delete == ""):
        #hillify = "hillify"
	if (ops == "add"):
            update_spa_sql = """INSERT INTO spectrum_annotation (compound_id,mz,formula,inchi,confirmed_by_labeling,precursor_atoms_retained,comment,mass_isotopomer_max) VALUES (%s,%s,hillify(%s),%s,%s,%s,%s,%s) RETURNING id"""  
	if (ops == "update"):
	    update_spa_sql = """UPDATE spectrum_annotation SET compound_id=%s,mz=%s,formula=hillify(%s),inchi=%s,confirmed_by_labeling=%s,precursor_atoms_retained=%s,comment=%s,mass_isotopomer_max=%s WHERE id = %s"""      
        #update_spa_sql = """INSERT INTO spectrum_annotation (compound_id,mz,formula,inchi,confirmed_by_labeling,precursor_atoms_retained,comment,mass_isotopomer_max) VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id""" 
    else:
        update_spa_sql = """DELETE spectrum_annotation where compound_id = %s and mz = %s"""
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config)) 
    cur = con.cursor()
    if (ops == "add"):
        cur.execute(update_spa_sql,(compound_id, mz, formula, inchi, label_confirm, precursor_atoms_retained,comment, isotope_mass_max))
        spectrum_annotation_id = cur.fetchone()[0]
    if (ops == "update"):
        cur.execute(update_spa_sql,(compound_id, mz, formula, inchi, label_confirm, precursor_atoms_retained,comment, isotope_mass_max,spectrum_annotation_id))
    cur.execute("commit")
    print "Content-type: text/html;charset=utf-8\r\n"
    #print "post select - process result set " + time.asctime( time.localtime(time.time()) )
    pa = {}
    pa['_spaid'] = str(spectrum_annotation_id)
    pa['_status'] = "200"
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Update Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
